package Interview;

import java.util.ArrayList;
import java.util.List;

/**
 * 股神问题 最大购买收益
 * @author: leiwenkang02@meituan.com
 * @date: 2018/4/12
 * @time: 14:23
 */
public class MaxProfit {
    public static void main(String[] args) {
        int[] array = {0,12,4,5,1,18,25,4,8,9};
        System.out.println(getMaxProfit(array));
        System.out.println(getMaxProfit2(array));
    }

    /*
    O(n^2) 常规解法
     */
    public static int getMaxProfit(int[] array) {
        if (array == null || array.length == 1) {
            return -1;
        }
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < array.length; i++) {
            for (int j = i + 1; j < array.length; j++) {
                list.add(array[j] - array[i]);
            }
        }
        int maxProfit = list.get(0);
        for (int i = 0; i < list.size(); i++) {
            if (maxProfit < list.get(i)) {
                maxProfit = list.get(i);
            }
        }
        return maxProfit;
    }


    public static int getMaxProfit2(int[] array) {
        if (array == null || array.length == 1) {
            return  - 1;
        }
        int min = array[0];
        int maxProfit = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[i] < min) {
                min = array[i];
            } else if (maxProfit < (array[i] - min)) {
                maxProfit = array[i] - min;
            }
        }
        return maxProfit;
    }
}
